package com.baitiaojun.security.core.utils;

import com.baitiaojun.security.core.domain.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class SecurityUtils {

    /**
     * 获取已经验证过的用户id
     * @return
     */
    public static Long getUserId() {
        return getLoginUser().getUserId();
    }

    /**
     * 获取已经验证过的用户名
     * @return
     */
    public static String getUserName() {
        return getLoginUser().getUsername();
    }

    /**
     * 获取已经验证过的用户信息
     * @return
     */
    public static LoginUser getLoginUser() {
        return (LoginUser) getAuthentication().getPrincipal();
    }

    /**
     * 获取存储用户信息的上下文
     * @return
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 给原始密码加密, 使用hash算法+随机salt生成加密密码, 加密后不可逆
     * @param password
     * @return
     */
    public static String encodePassword(String password) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 比较明文密码和加密后的密码是否相同
     * @param rawPassword
     * @param encodePassword
     * @return
     */
    public static boolean match(String rawPassword, String encodePassword) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodePassword);
    }

    public static void main(String[] args) {
        System.out.println(encodePassword("admin123"));
//        System.out.println(match("123456", "$2a$10$bu8GOWcNaMI76pgI8lvtDuu0KR9IE.SmRobWkLunnoxVRzvR0Dn/a"));
    }
}